package com.example.qxfw.qxybzz.service.Impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dmgis.service.DmServiceConnector;
import com.dmgis.util.DateTime;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.dmgis.constant.ContourMapType;
import com.example.qxfw.common.dmgis.constant.InterType;
import com.example.qxfw.common.dmgis.layer.ContourMapLayer;
import com.example.qxfw.common.dmgis.layer.RainContourMapLayer;
import com.example.qxfw.common.dmgis.vo.PointVo;
import com.example.qxfw.common.util.DocModelUtil;
import com.example.qxfw.common.util.FileUtil;
import com.example.qxfw.common.util.TxtFileManager;
import com.example.qxfw.qxybzz.entity.*;
import com.example.qxfw.qxybzz.mapper.*;
import com.example.qxfw.qxybzz.service.ContourMapService;
import com.example.qxfw.qxybzz.service.MeteorologyMaterialsService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 14559
 * @version 1.0
 * @description: TODO
 * @date 2024/12/11 17:00
 */
@Service
public class MeteorologyMaterialsServiceImpl implements MeteorologyMaterialsService {

    @Value("${dmgis.ip}")
    private String dmgisIp;

    @Value("${dmgis.port}")
    private String dmgisPort;

    @Value("${dmgis.pluginpath}")
    private String pluginpath;

    @Value("${dmgis.image_url}")
    private String imgUrl;

    @Value("${dmgis.active}")
    private String active;

    @Value("${dmgis.ngfile_url}")
    private String ngfile_url;

    @Resource
    private MeteorologyMaterialsMapper materialsMapper;

    @Resource
    private MeteorologyDataMapper meteorologyDataMapper;

    @Resource
    private CommonMapper commonMapper;

    @Autowired
    private BaseProductMapper baseProductMapper;

    @Qualifier("mongoSecondTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private SummaryProductMapper summaryProductMapper;

    @Autowired
    private TxtFileManager txtFileManager;

    @Autowired
    private ContourMapService contourMapService;

    @Override
    public List<jobmodel> getJobModels(String onetype) {
        return materialsMapper.getJobModels(onetype);
    }

    @Override
    public List<SummaryProduct> getHistoryProduct(String onetype, String twotype) {
        return materialsMapper.getHistoryProduct(onetype, twotype);
    }

    @Override
    public ArrayList getMsgAllData(msgparam msg) {
        ArrayList arraylist = new ArrayList();
        try {
            String img=null;
            List<MeteorologyData> list = meteorologyDataMapper.getAllStaMsgTable(msg);//查询站点排名列表
            List<MeteorologyData> countryData = list.stream()
                    .filter(data -> data.getStationid().startsWith("5"))
                    .collect(Collectors.toList());//国家站排名
            String statisticContent = meteorologyDataMapper.getStatisticsContent(msg);//右侧查询统计文本
            String skContent = "";
            if (msg.getStarttime().contains("T")) {
                // 解析字符串为 ZonedDateTime
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(msg.getStarttime());
                // 定义目标格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 格式化为目标格式的字符串
                String formattedDate = zonedDateTime.format(formatter);
                msg.setStarttime(formattedDate);
            }
            if (msg.getEndtime().contains("T")) {
                // 解析字符串为 ZonedDateTime
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(msg.getEndtime());
                // 定义目标格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 格式化为目标格式的字符串
                String formattedDate = zonedDateTime.format(formatter);
                msg.setEndtime(formattedDate);
            }
            DateTime startDate = DateTime.parseDateTime(msg.getStarttime(), "yyyy-MM-dd HH:mm:ss");
            DateTime endDate = DateTime.parseDateTime(msg.getEndtime(), "yyyy-MM-dd HH:mm:ss");
            DateTime qhtztjtime = endDate;

            qhtztjtime = qhtztjtime.AddHours(-1);//日数据当天的没有，需要往前一天
            msg.setYear(qhtztjtime.GetYear());
            msg.setMonth(qhtztjtime.GetMonth());
            msg.setDay(qhtztjtime.GetDay());
            List<MeteorologyData> qhtztj = new ArrayList<>();
            List<MeteorologyData> qhtztjResult = new ArrayList<>();
            if (msg.getType() == 1) {
                qhtztj = meteorologyDataMapper.getClimaticYear(msg);//查询气候特征统计 年
            } else if (msg.getType() == 2) {
                msg.setLastday(1);
                qhtztj = meteorologyDataMapper.getClimaticMonthTd(msg);//查询气候特征统计 月
            } else {
                if (qhtztjtime.GetDay() >= 21)
                    msg.setLastday(21);
                else if (qhtztjtime.GetDay() >= 11)
                    msg.setLastday(11);
                else
                    msg.setLastday(1);
                qhtztj = meteorologyDataMapper.getClimaticMonthTd(msg);//查询气候特征统计 旬
            }
            if (msg.getStationtype() == 1) {
                qhtztjResult = qhtztj.stream()
                        .filter(data -> data.getStationid().startsWith("5"))
                        .collect(Collectors.toList());//国家站排名
            } else if (msg.getStationtype() == 2) {
                qhtztjResult = qhtztj.stream()
                        .filter(data -> !data.getStationid().startsWith("5"))
                        .collect(Collectors.toList());//区域站排名
            } else if (msg.getStationtype() == 3) {
                qhtztjResult = qhtztj;//区域站排名
            }

            String elementtype = "";
            ContourMapType contourMapType=null;
            switch (msg.getDataType()){
                case 1:elementtype = "平均气温";contourMapType=ContourMapType.TEMP;break;
                case 2:elementtype = "最高气温";contourMapType=ContourMapType.MAX_AT;break;
                case 3:elementtype = "最低气温";contourMapType=ContourMapType.MIN_AT;break;
                case 4:elementtype = "累积降水";contourMapType=ContourMapType.RAIN_FALL;break;
                case 5:elementtype = "最大小时雨强";contourMapType=ContourMapType.MAX_RAIN_FALL;break;
                case 6:elementtype = "最大风";contourMapType=ContourMapType.MAX_WIND;break;
                case 7:elementtype = "最小能见度";contourMapType=ContourMapType.VISIBILITY;break;
                case 8:elementtype = "最高气温";contourMapType=ContourMapType.E_S_WIND;break;
                case 9:elementtype = "极大风";contourMapType=ContourMapType.E_S_WIND;break;
            }
//            if (contourMapType!=null&&!list.isEmpty()){
//                    List<PointVo> points = list.stream().map(item -> new PointVo(item.getLongitude(), item.getLatitude(), item.getValue())).collect(Collectors.toList());
//                    ContourMap contourMap = contourMapService.cenerateContourMaps(points,this.formatStr(msg.getStarttime())+" 至 "+this.formatStr(msg.getEndtime()), InterType.KIG, contourMapType);
//                    if (contourMap!=null){
//                        img=Base64.getEncoder().encodeToString(contourMap.getData());
//                    }
//            }

            String maxcenter = "";
            Double maxvalue = 0.0;
            for (MeteorologyData mete : list) {
                maxcenter = mete.getStationname().startsWith(mete.getCounty()) ? mete.getStationname() : mete.getCounty() + mete.getStationname();
                maxvalue = mete.getValue();
            }
            skContent = startDate.toDateTimeString("dd日HH时")
                    + "至" + endDate.toDateTimeString("dd日HH时")
                    + "，" + elementtype + "在" + maxcenter + maxvalue + contourMapType.getUnit() + "。";
            String countryInfo = "城区：";
            for (MeteorologyData mete : countryData) {
                countryInfo += mete.getCounty() + mete.getValue() + contourMapType.getUnit() + "、";
            }
            if (countryInfo.endsWith("、")) countryInfo = countryInfo.substring(0, countryInfo.length() - 1) + "。";
            skContent += countryInfo;
            arraylist.add(list);
            arraylist.add(countryData);
            arraylist.add(statisticContent);
            arraylist.add(skContent);
            arraylist.add(qhtztjResult);
//            String txtPath = getImgUrl(list, elementtypelegend, "xinjiangYiliQx");
//            DmServiceConnector conn = new DmServiceConnector(dmgisIp, dmgisPort);
//            String uniqueno = conn.getCallPlugin("service", "contour",
//                    "GetInterpolationWork|" + txtPath);
//            String jpgImgurl = conn.getCallPlugin("service", "contour",
//                    "GetPrjPic2|" + uniqueno
//                            + "|xinjiangYiliQx|500|500|80.1620579912833,42.2578164469715,84.948426730809,44.8427495221728|1|1|1|1|"
//                            + elementtype + "|" + unit + "|" + msg.getStarttime() + "|" + msg.getEndtime());
//            System.out.println(jpgImgurl);
            if (img==null){
                img=FileUtil.encodeImageToBase64(imgUrl + "demo.png");
            }
            arraylist.add(img);
            return arraylist;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getImgUrl(List<MeteorologyData> list, String elementType, String serverName) {
        try {
            List<MeteorologyData> msgMediumSmallScaleList = list;
            List<ContourSetting> contourSettingList = commonMapper.queryByElementType(elementType);
            StringBuilder txt = new StringBuilder();
            // 添加基本参数
            txt.append("[基本参数]\n");
            //点的个数
            txt.append(msgMediumSmallScaleList.size()).append(",");
            //分级数
            txt.append(contourSettingList.size()).append(",");
            //服务名
            txt.append(serverName + ",1,1.5,5,1,0,0,1\n");
            // 添加数据
            txt.append("[数据]\n");
            msgMediumSmallScaleList.forEach(longitudeLatitudeValue -> {
                txt.append(longitudeLatitudeValue.getLongitude()).append("\t")
                        .append(longitudeLatitudeValue.getLatitude()).append("\t")
                        .append(longitudeLatitudeValue.getValue()).append("\n");
            });
            // 添加分级参数
            txt.append("[分级参数]\n");
            contourSettingList.forEach(contourSetting -> {
                txt.append(contourSetting.getElementvalue()).append(",")
                        .append(contourSetting.getElementcolor()).append(",")
                        .append(contourSetting.getElementcolor()).append(",")
                        .append("1,0,")
                        .append(contourSetting.getElementcolor()).append(",")
                        .append("0,0,0,0").append("\n");
            });
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            // 生成文件名，格式为时间+RefinedForecastingController
            String txtName = dateFormat.format(new Date());
            String txtPath = null;
            txtPath = txtFileManager.writeDataToTxtFile(txt.toString(), txtName);
            //文件夹目录
            String homePath = TxtFileManager.extractFolderPath(txtPath);
            // 一小时删除任务
            TxtFileManager.cleanupTempFiles(homePath, 3600000);

            String url = ngfile_url + "/" + txtName + ".txt";
            return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<MeteorologyData> getMsgClimaticCharacteristicsData(msgparam msg) {
        DateTime endDate = null;
        try {
            if (msg.getEndtime().contains("T")) {
                // 解析字符串为 ZonedDateTime
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(msg.getEndtime());
                // 定义目标格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 格式化为目标格式的字符串
                String formattedDate = zonedDateTime.format(formatter);
                msg.setEndtime(formattedDate);
            }
            endDate = DateTime.parseDateTime(msg.getEndtime(), "yyyy-MM-dd HH:mm:ss");
            DateTime qhtztjtime = endDate;

            qhtztjtime = qhtztjtime.AddHours(-1);//日数据当天的没有，需要往前一天
            msg.setYear(qhtztjtime.GetYear());
            msg.setMonth(qhtztjtime.GetMonth());
            msg.setDay(qhtztjtime.GetDay());
            if (msg.getType() == 1) {
                return meteorologyDataMapper.getMsgClimaticCharacteristicsData(msg);// 年
            } else if (msg.getType() == 2) {
                msg.setLastday(1);
                return meteorologyDataMapper.getMsgClimaticCharacteristicsDataMonthTd(msg);//查询气候特征统计 月
            } else {
                if (qhtztjtime.GetDay() >= 21)
                    msg.setLastday(21);
                else if (qhtztjtime.GetDay() >= 11)
                    msg.setLastday(11);
                else
                    msg.setLastday(1);
                return meteorologyDataMapper.getMsgClimaticCharacteristicsData(msg);//查询气候特征统计 旬
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<MeteorologyFcstData> getGridFcstData(gridfcstparam param) {
        try {
            if (param.getNtimes() % 24 == 0)
                param.setForecasttype(12);
            else
                param.setForecasttype(param.getNtimes());
            int hour = Integer.parseInt(param.getTimechar()) + param.getNtimes();
            DateTime dateTime = DateTime.parseDateTime(param.getDatechar()).AddHours(hour);
            param.setDatechar(dateTime.toDateString());
            param.setNtimes(dateTime.GetHour());
            param.setStationidArray(Arrays.asList(param.getStationids().split(",")));
            List<SmallScaleStation> countyStation = commonMapper.getCountyStation("");

            List<SmallScaleStation> tourStation=materialsMapper.getTourStation("");
            List<SmallScaleStation> trafficStation=materialsMapper.getTrafficStation("");

            Map<String, String> map = new HashMap<>();

            for (SmallScaleStation station : countyStation) {
                map.put(station.getStationid(), station.getStationname());
            }
            for (SmallScaleStation station : tourStation){
                map.put(station.getStationid(), station.getStationname());
            }
            for (SmallScaleStation station : trafficStation){
                map.put(station.getStationid(), station.getStationname());
            }

            List<MeteorologyFcstData> meteorologyFcstData = materialsMapper.MeteorologyFcstData(param);
            for (MeteorologyFcstData data : meteorologyFcstData) {
                data.setStationid(data.getStationid().trim());
                data.setStationname(map.get(data.getStationid()));
            }
            return meteorologyFcstData;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<job_standard> getJobStandard() {
        return materialsMapper.getJobStandard();
    }


    @Override
    public void addJobStandard(String type, String grading, String context) {
        materialsMapper.addJobStandard(type, grading, context);
    }


    @Override
    public Object makeCommonMaterialDoc(String jsonData, MultipartFile[] images) {
        CommonMater commonMater = JSON.parseObject(jsonData, CommonMater.class);
        if (commonMater == null)
            return SysResult.fail("传入数据为空！");

        String templatePath;
        //产品路径
        String targetPath;

        String doctype = "市级";
        String doctype2 = "气象服务信息";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  // 指定日期格式
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");  // 指定日期格式
        SimpleDateFormat sdf2 = new SimpleDateFormat("M月d日H时");  // 指定日期格式
        SimpleDateFormat sdf3 = new SimpleDateFormat("d日H时");  // 指定日期格式
        SimpleDateFormat sdfyear = new SimpleDateFormat("yyyy");  // 指定日期格式
        SimpleDateFormat sdfmonth = new SimpleDateFormat("M");  // 指定日期格式
        SimpleDateFormat sdfday = new SimpleDateFormat("d");  // 指定日期格式
        SimpleDateFormat sdfhour = new SimpleDateFormat("H");  // 指定日期格式

        try {
            Date date = sdf.parse(commonMater.getDatetime());
            Date startDate = sdf.parse(commonMater.getStarttime());
            Date endDdate = sdf.parse(commonMater.getEndtime());

            //获取文档名称 20240819-气象服务信息(46)天气实况及近期天气预报
            String productName = sdf1.format(date) + "-" + doctype2 + "(" + commonMater.getQishu() + ")天气实况及近期天气预报.docx";

            ApplicationHome applicationHome = new ApplicationHome(this.getClass());
            if (active.equals("dev")) {
                templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                        "\\src\\main\\resources\\templates\\" + doctype2 + "模板.docx";
                targetPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                        "\\src\\main\\resources\\temp\\" + productName;
            } else {
                templatePath = applicationHome.getSource().getParentFile() +
                        "\\resources\\templates\\" + doctype2 + "模板.docx";
                targetPath = applicationHome.getSource().getParentFile() +
                        "\\resources\\temp\\" + productName;
            }

            //申请资源
            FileInputStream templateStream = new FileInputStream(templatePath);
            XWPFDocument document = new XWPFDocument(templateStream);
            FileOutputStream targetSteam = new FileOutputStream(targetPath);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            //段落替换
            String[] placeholders = new String[]{"【年】", "【期】", "【月】", "【日】", "【时】"
                    , "【实况文本】"
                    , "【预报文本】"
                    , "【措施建议】"
                    , "【表一标题】"
                    , "【表二标题】"
                    , "【图一标题】"};
            String stryear = sdfyear.format(date);
            String strmonth = sdfmonth.format(date);
            String strday = sdfday.format(date);
            String strhour = sdfhour.format(date);
            String table1 = "", table2 = "", pic1 = "";

            String elementtype = "";
            String unit = "";
            if (commonMater.getDataType() == 1) {
                elementtype = "平均气温";
                unit = "℃";
            }
            if (commonMater.getDataType() == 2) {
                elementtype = "最高气温";
                unit = "℃";
            }
            if (commonMater.getDataType() == 3) {
                elementtype = "最低气温";
                unit = "℃";
            }
            if (commonMater.getDataType() == 4) {
                elementtype = "累积降水";
                unit = "mm";
            }
            if (commonMater.getDataType() == 5) {
                elementtype = "最大小时雨强";
                unit = "mm/h";
            }
            if (commonMater.getDataType() == 6) {
                elementtype = "最大风";
                unit = "m/s";
            }
            if (commonMater.getDataType() == 7) {
                elementtype = "最小能见度";
                unit = "m";
            }
            if (commonMater.getDataType() == 8) {
                elementtype = "最大积雪深度";
                unit = "cm";
            }
            if (commonMater.getDataType() == 9) {
                elementtype = "极大风";
                unit = "m/s";
            }

            if (StringUtils.isNotBlank(commonMater.getSkData2()))
                table1 = "表1 伊犁河谷各县市城区" + sdf2.format(startDate) + "至" + sdf3.format(endDdate) + elementtype + "（单位：" + unit + "）";
            if (StringUtils.isNotBlank(commonMater.getSkData1()))
                table2 = "表2 伊犁河谷部分区域自动站" + sdf2.format(startDate) + "至" + sdf3.format(endDdate) + elementtype + "（单位：" + unit + "）";
            if (images.length > 0)
                pic1 = "图1 伊犁河谷" + sdf2.format(startDate) + "至" + sdf3.format(endDdate) + elementtype + "分布图（单位:" + unit + "）";
            //替换内容
            String[] replacements = new String[]{stryear, commonMater.getQishu(), strmonth.replaceFirst("^0+", ""),
                    strday.replaceFirst("^0+", ""), strhour, commonMater.getSkcontent(),
                    commonMater.getYbcontent(), commonMater.getCscontent(), table1, table2, pic1};

            List<XWPFParagraph> paragraphs = document.getParagraphs();
            // 替换段落内容
            for (int i = 0; i < paragraphs.size(); i++) {
                XWPFParagraph paragraph = paragraphs.get(i);
                //获取段落内容
                String text = paragraph.getText();

                //替换文字内容
                DocModelUtil.replaceTextInParagraph(paragraph, placeholders, replacements);

                if (StringUtils.isNotBlank(commonMater.getSkData2()) && text.equals("【表一】")) {
                    //json字符串转换为对象列表
                    List<MeteorologyData> skList = JSON.parseArray(commonMater.getSkData2(), MeteorologyData.class);
                    //获取下标
                    XmlCursor cursor = paragraph.getCTP().newCursor();
                    XWPFTable table = document.insertNewTbl(cursor);
                    //添加表头
                    XWPFTableRow row_0 = table.getRow(0);
                    row_0.getCell(0).setText("县市");
                    row_0.addNewTableCell().setText(elementtype);
                    row_0.addNewTableCell().setText("县市");
                    row_0.addNewTableCell().setText(elementtype);
                    for (int kk = 0; kk < skList.size(); kk += 2) {
                        XWPFTableRow dataRow = table.createRow();
                        dataRow.getCell(0).setText(skList.get(kk).getCounty());
                        dataRow.getCell(1).setText(String.valueOf(skList.get(kk).getValue()));
                        if (kk + 1 == skList.size())
                            continue;
                        dataRow.getCell(2).setText(skList.get(kk + 1).getCounty());
                        dataRow.getCell(3).setText(String.valueOf(skList.get(kk + 1).getValue()));
                    }
                    DocModelUtil.setTableLocation(table, "center");
                    DocModelUtil.setCellLocation(table, "CENTER", "center");
                    document.removeBodyElement(document.getPosOfParagraph(paragraph));
                }

                if (StringUtils.isNotBlank(commonMater.getSkData1()) && text.equals("【表二】")) {
                    //json字符串转换为对象列表
                    List<MeteorologyData> skList = JSON.parseArray(commonMater.getSkData1(), MeteorologyData.class);
                    //获取下标
                    XmlCursor cursor = paragraph.getCTP().newCursor();
                    XWPFTable table = document.insertNewTbl(cursor);
                    //添加表头
                    XWPFTableRow row_0 = table.getRow(0);
                    row_0.getCell(0).setText("县市");
                    row_0.addNewTableCell().setText("乡镇");
                    row_0.addNewTableCell().setText("站名");
                    row_0.addNewTableCell().setText(elementtype);
                    skList.forEach(sk -> {
                        XWPFTableRow dataRow = table.createRow();
                        dataRow.getCell(0).setText(sk.getCounty());
                        dataRow.getCell(1).setText(sk.getTown());
                        dataRow.getCell(2).setText(sk.getStationname());
                        dataRow.getCell(3).setText(String.valueOf(sk.getValue()));
                    });
                    DocModelUtil.setTableLocation(table, "center");
                    DocModelUtil.setCellLocation(table, "CENTER", "center");
                    document.removeBodyElement(document.getPosOfParagraph(paragraph));
                }

                //插入图片
                if (text.equals("【图一】")) {
                    MultipartFile imageFile = images[0];
                    DocModelUtil.insertImgToWord(paragraph, document, imageFile);
                }
            }
            // 将生成的文档保存到输出文件
            document.write(targetSteam);
            targetSteam.close();

            //保存基本产品表数据
            SummaryProduct summaryProduct = new SummaryProduct();
            summaryProduct.setYear(Integer.parseInt(stryear));
            summaryProduct.setProductname(productName);
            summaryProduct.setProducttype(doctype);
            summaryProduct.setProducttype2(doctype2);//
            summaryProduct.setForecasttime(date);
            summaryProduct.setMaketime(new Date());
            summaryProduct.setStatus(1);
            summaryProduct.setSkcontent(commonMater.getSkcontent());
            summaryProduct.setYbcontent(commonMater.getYbcontent());
            summaryProduct.setCsjycontent(commonMater.getCscontent());
            summaryProduct.setMaker("admin");
            summaryProductMapper.insert(summaryProduct);
            byte[] buffer = new byte[1024];
            int bytesRead;
            FileInputStream inputStream = new FileInputStream(targetPath);
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            //保存到mongodb库中
            HyDocFile hyDocFile = new HyDocFile();
            hyDocFile.setData(byteArray);
            hyDocFile.setTable_name("summary_product");
            hyDocFile.setId(String.valueOf(summaryProduct.getId()));
            mongoTemplate.save(hyDocFile);
            // 设置前端响应
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", productName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("文档生成失败");
        }
        return null;
    }


    @Override
    public List<SmallScaleStation> getTourStation(String advname) {
        return materialsMapper.getTourStation(advname);
    }

    @Override
    public List<SmallScaleStation> getTrafficStation(String advname) {
        return materialsMapper.getTrafficStation(advname);
    }



    private String formatStr(String time){
        char[] arrChar={'年','月','日','时'};
        int[] index={4,7,10,13};
        if (StringUtils.isNotBlank(time)&&time.length()>13){
            String sub = time.substring(0, 14);
            char[] charArray = sub.toCharArray();
            for (int i = 0; i < index.length; i++) {
                charArray[index[i]]=arrChar[i];
            }
            return new String(charArray);
        }
        return null;
    }
}
